package com.greejoy.score.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

import com.greejoy.score.MyApplication;
import com.greejoy.score.R;
import com.greejoy.score.service.WebsocketService;

public class SettingActivity extends AppCompatActivity implements View.OnClickListener {

    private MyApplication app;
    private EditText et_http;
    private EditText et_ws;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);

        app = MyApplication.getInstance();

        et_http = findViewById(R.id.et_http);
        et_ws = findViewById(R.id.et_ws);
        String httpUrl = app.dataMap.get("httpUrl");
        et_http.setText(httpUrl);
        String wsUrl = app.dataMap.get("wsUrl");
        et_ws.setText(wsUrl);

        findViewById(R.id.btn_setting).setOnClickListener(this);
        findViewById(R.id.btn_ip_1).setOnClickListener(this);
        findViewById(R.id.btn_ip_2).setOnClickListener(this);
        findViewById(R.id.btn_ip_3).setOnClickListener(this);
    }

    @Override
    public void onClick(View view){
        if(view.getId() == R.id.btn_setting){
            String httpUrl = et_http.getText().toString();
            String wsUrl = et_ws.getText().toString();

            // 更新app全局map
            app.dataMap.put("httpUrl", httpUrl);
            app.dataMap.put("wsUrl", wsUrl);

            // 更新shared preferences
            SharedPreferences sharedPreferences = getSharedPreferences("config", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString("httpUrl", httpUrl);
            editor.putString("wsUrl", wsUrl);
            editor.apply();

            startService(new Intent(this, WebsocketService.class));

            // 跳转比赛首页
            startActivity(new Intent(this, MainActivity.class));
            finish();
        }else if(view.getId() == R.id.btn_ip_1){
            et_http.setText("http://www.greejoy.com/js/");
            et_ws.setText("ws://www.greejoy.com/js/js/ws/server");
        }else if(view.getId() == R.id.btn_ip_2){
            et_http.setText("http://192.168.188.200:8088/");
            et_ws.setText("ws://192.168.188.200:8088/js/ws/server");
        }else if(view.getId() == R.id.btn_ip_3){
            et_http.setText("http://192.168.10.200:8088/");
            et_ws.setText("ws://192.168.10.200:8088/js/ws/server");
        }
    }


    @Override
    public void onBackPressed() {
        // 跳转比赛首页
        startActivity(new Intent(this, MainActivity.class));
        finish();
    }

}